<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="`正在修改用户[${form.data.userName}]的密码`"
    width="35%"
    align-center
    @closed="handleCancel"
  >
    <el-form ref="refForm" :model="form.data" :rules="form.rules" label-position="right">
      <el-form-item prop="password" label="新密码">
        <el-input v-model="form.data.password" placeholder="请输入密码">
          <template #append>
            <el-link :underline="false" @click="handleGeneratePwd">随机生成</el-link>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSave">保 存</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { withDefaults, computed, reactive, ref, nextTick } from 'vue'
import { ElDialog, ElMessage, ElForm, ElFormItem, ElInput, ElLink } from 'element-plus'
import { util } from '@/utils'
import { userApi } from '@/api/modules/system/user'
import type { User } from '@/api/modules/system/user'

const props = withDefaults(defineProps<{ visible: boolean }>(), {
  visible: false
})
const emits = defineEmits(['update:visible'])

const refForm = ref()
const form = reactive<{ data: User; rules: any }>({
  data: {} as User,
  rules: {
    password: [{ required: true, message: '请输入新密码' }]
  }
})
const dialogVisible = computed(() => props.visible)

const handleSave = () => {
  refForm.value.validate((valid: boolean) => {
    if (valid) {
      // log.action('修改密码')
      userApi.updatePwd(form.data).then(resp => {
        if (resp.success) {
          ElMessage.success(`用户[${form.data.userName}]的密码已修改`)
          handleCancel()
        } else {
          ElMessage.error(resp.message)
        }
      })
    }
  })
}

const handleCancel = () => {
  form.data = {} as User
  refForm.value.resetFields()
  emits('update:visible', false)
}

const setFormData = (data: User) => {
  nextTick(() => (form.data = util.cloneObject(data)))
}

const handleGeneratePwd = () => {
  form.data.password = util.randomStr(8)
}
defineExpose({ setFormData })
</script>

<style lang="scss" scoped></style>
